/**
 * @author 艾尼亚尔
 * @date 2025/8/7
 * @description
 */
import {defineStore} from "pinia";
import {store} from "@/stores/index.ts";
import {getLocalStorage, setLocalStorage} from "@/utils/storage.ts";
import type {RouteRecordRaw} from "vue-router";
import {generateRoutesByServer, generatorMenu} from '@/utils'
import type {CustomMenuOption, ServerRouteItem} from '@/types/router';

import BaseRouters from '@/router/routers.ts'


interface AppState {
    appTheme:'light' | 'dark',
    menuStyle: number,
    menuCollapsed: boolean;
    isProd: boolean;
    copyright: string;
    icp_url: string;
    tel_email_qq: string;
    menus: CustomMenuOption[]; //菜单
    tabs: SimpleRoute[];
    routers: RouteRecordRaw[];
    addRouters: RouteRecordRaw[];
    isDynamicAddedRoute: boolean;

}

export const UseAppStore = defineStore('app', {
    state: (): AppState => ({
        appTheme: getLocalStorage("app_theme") || 'light',
        menuStyle: 2,
        copyright: '',
        icp_url: '',
        tel_email_qq: '',
        isProd: import.meta.env.PROD,
        menuCollapsed: getLocalStorage("menuCollapsed") || false,
        menus: [],
        tabs: getLocalStorage("tab_list") || [],
        routers: [],
        addRouters: [],
        isDynamicAddedRoute: false,
    }),
    getters: {
        getMenu(state: AppState): CustomMenuOption[] {
            return generatorMenu(state.routers)
        },
    },
    actions: {
        //暗色模式/亮色模式
        changeTheme(){
            const theme = this.appTheme == 'light' ? 'dark' : 'light';
            this.appTheme=theme;
            setLocalStorage("app_theme", theme);
            if(theme === 'dark') {
                document.documentElement.classList.add('dark')
            }else{
                document.documentElement.classList.remove('dark')
            }
        },
        // 设置动态路由
        setRouters(routers: RouteRecordRaw[]) {
            this.addRouters = routers;
            this.routers = [...BaseRouters, ...routers];
        },
        setMenuCollapsed() {
            this.menuCollapsed = !this.menuCollapsed;
            setLocalStorage("menuCollapsed", this.menuCollapsed);
        },
        //更新tabs
        updateTabs(tabs: SimpleRoute[]) {
            setLocalStorage("tab_list", tabs);
            this.tabs = tabs;
        },
        // 关闭当前页
        CloseCurrentTabs(route: SimpleRoute) {
            const index = this.tabs.findIndex((item) => item.fullPath === route.fullPath);
            this.tabs.splice(index, 1);
            this.updateTabs(this.tabs)
        },
        //关闭其他
        CloseOtherTabs(current_route: SimpleRoute) {
            if (current_route.fullPath === '/home' && current_route.name === 'home') {
                this.CloseAllTabs()
            } else {
                const filter_tabs = this.tabs.filter((item) => item.fullPath === '/home' || item.fullPath === current_route.fullPath && item.name === current_route.name);
                this.tabs = filter_tabs;
                this.updateTabs(filter_tabs)
            }
        },
        //关闭全部
        CloseAllTabs() {
            const filter_tabs = this.tabs.filter((item) => item.fullPath === '/home');
            this.tabs = filter_tabs;
            this.updateTabs(filter_tabs)
        },
        //添加tabs
        addTabs(route: SimpleRoute) {
            const isExists = this.tabs.some((item: SimpleRoute) => item.name === route.name);
            if (isExists && route.name !== "notFound" && route.name !== "forbidden" && route.name !== "login") {
                const index = this.tabs.findIndex((item: SimpleRoute) => item.name === route.name);
                this.tabs[index] = route;
            } else if (!isExists && route.name !== "notFound" && route.name !== "forbidden" && route.name !== "login") {
                this.tabs.push(route);
            }
            this.updateTabs(this.tabs)
        },
        //是否动态添加
        setDynamicAddedRoute(added: boolean) {
            this.isDynamicAddedRoute = added;
        },
        //处理动态路由
        async generateRoutes() {
            const routers: ServerRouteItem[] = getLocalStorage("routers_list") || [];
            const asyncRoutes: RouteRecordRaw[] = generateRoutesByServer(routers);
            this.setRouters(asyncRoutes);
            return asyncRoutes
        },
    }
})

export function appStoreWidthOut() {
    return UseAppStore(store);
}
